<template>
  <view class="my-container">

    <!-- 头像和登录/注册（已登录则进入编辑页） -->
    <view class="my-profile-card" @click="handleProfileClick" @tap="handleProfileClick">
      <image class="my-avatar" :src="displayAvatar" mode="aspectFill" @error="onAvatarError" @load="onAvatarLoad"></image>
      <view class="my-profile-info">
        <view class="my-profile-name">
          <text v-if="!isLoggedIn">登录|注册</text>
          <text v-else>欢迎回来，{{ userInfo.nickName }}</text>
        </view>
        <view class="my-profile-desc">
          <text v-if="!isLoggedIn">未登录，请登录！</text>
          <text v-else>点击编辑个人信息</text>
        </view>
      </view>
    </view>

    <!-- 菜单列表 -->
    <view class="my-menu">
      <view class="my-menu-item" @click="goToFeedback">
        <image class="my-menu-icon-img" src="/static/me/意见反馈.png" mode="aspectFit"></image>
        <text class="my-menu-title">意见反馈</text>
        <text class="my-menu-arrow">></text>
      </view>
      <view class="my-menu-item" @click="goToService">
        <image class="my-menu-icon-img" src="/static/me/客服.png" mode="aspectFit"></image>
        <text class="my-menu-title">联系客服</text>
        <text class="my-menu-arrow">></text>
      </view>
      <view class="my-menu-item" @click="goToSettings">
        <image class="my-menu-icon-img" src="/static/me/设置.png" mode="aspectFit"></image>
        <text class="my-menu-title">设置</text>
        <text class="my-menu-arrow">></text>
      </view>
    </view>
  </view>
</template>

<script>
import { API_BASE } from '@/config/config.js'
import request from '@/utils/request'

export default {
  data() {
    return {
      isLoggedIn: false,
      userInfo: {
        nickName: '',
        avatar: ''
      },
      tokenValid: false // New: whether token is valid
    }
  },
  onShow() {
    const token = uni.getStorageSync('token');
    this.isLoggedIn = !!token;
    
    // Validate token if logged in
    if (this.isLoggedIn) {
      request({
        url: '/system/user/profile', // Test API that requires auth
        method: 'GET'
      }).then(res => {
        if (res && res.code === 200) {
          this.tokenValid = true;

        } else {
          this.tokenValid = false;

          uni.removeStorageSync('token');
          uni.removeStorageSync('userInfo');
          this.isLoggedIn = false;
          uni.showToast({
            title: '登录已过期，请重新登录',
            icon: 'none'
          });
          setTimeout(() => {
            uni.reLaunch({ url: '/pages/login' });
          }, 1500);
        }
      }).catch(err => {
        this.tokenValid = false;

        uni.removeStorageSync('token');
        uni.removeStorageSync('userInfo');
        this.isLoggedIn = false;
        uni.showToast({
          title: '登录已过期，请重新登录',
          icon: 'none'
        });
        setTimeout(() => {
          uni.reLaunch({ url: '/pages/login' });
        }, 1500);
      });
    }
    
    // 获取用户信息
    let userInfo = uni.getStorageSync('userInfo') || {};
    

    
    // 强制修复存储中的错误头像URL格式
    if (userInfo.avatar) {
      let fixedAvatar = userInfo.avatar;
      
      // 修复各种可能的错误格式
      if (fixedAvatar.includes('/system/user/profile/avatar/')) {
        fixedAvatar = fixedAvatar.replace('/system/user/profile/avatar/', '/profile/avatar/');

      }
      
      if (fixedAvatar.includes('http://localhost:8050/system/user/profile/avatar/')) {
        fixedAvatar = fixedAvatar.replace('http://localhost:8050/system/user/profile/avatar/', '/profile/avatar/');

      }
      
      // 如果修复了，更新缓存和本地数据
      if (fixedAvatar !== userInfo.avatar) {
        userInfo = { ...userInfo, avatar: fixedAvatar };
        uni.setStorageSync('userInfo', userInfo);

      }
    }
    
    this.userInfo = userInfo;

  },
  computed: {
    displayAvatar() {
      let raw = (this.userInfo && this.userInfo.avatar) || ''

      
      if (!raw) {

        return ''
      }
      
      // Force fix to /profile/avatar/ path
      if (raw.includes('/system/user/profile/avatar/')) {
        raw = raw.replace('/system/user/profile/avatar/', '/profile/avatar/');

      }
      
      if (raw.includes('http://localhost:8050/system/user/profile/avatar/')) {
        raw = raw.replace('http://localhost:8050/system/user/profile/avatar/', '/profile/avatar/');

      }
      
      // Always use non-authenticated full URL
      const fullUrl = raw.startsWith('http') ? raw : `${API_BASE}${raw}`;

      return fullUrl + '?t=' + Date.now(); // Add timestamp to prevent caching
    }
  },
  created() {
    // 不再需要动态引入，直接使用导入的常量

  },
  methods: {
    handleProfileClick() {
      const hasToken = !!uni.getStorageSync('token')
      const loggedIn = this.isLoggedIn || hasToken

      if (loggedIn) {
        uni.navigateTo({ 
          url: '/pages/profile/edit',

          fail: (err) => {

            uni.showToast({ title: '打开编辑页失败', icon: 'none' })
          }
        })
      } else {
        this.goToLogin()
      }
    },
    goToLogin() {

      uni.navigateTo({ 
        url: '/pages/login?from=profile',
        success: (res) => {

        },
        fail: (err) => {

          uni.showToast({ title: '跳转失败，请重试', icon: 'none' });
        }
      });
    },
    goToFeedback() {
      // 跳转到意见反馈页面
    },
    goToService() {
      uni.navigateTo({ url: '/pages/profile/kefu' });
    },
    goToSettings() {
      uni.navigateTo({ url: '/pages/profile/settings' });
    },
    
    onAvatarLoad(e) {

    },
    
    onAvatarError(e) {

      // 如果头像加载失败，使用默认头像
      this.userInfo.avatar = '';
    }
  }
}
</script>
<style scoped>
.my-container {
  background: #fff;
  min-height: 100vh;
  padding: 0;
}
.my-title {
  text-align: center;
  font-size: 48rpx;
  font-weight: bold;
  margin: 40rpx 0 20rpx 0;
}
.my-profile-card {
  display: flex;
  align-items: center;
  background: #faf6f2;
  border-radius: 20rpx;
  margin: 0 24rpx 32rpx 24rpx;
  padding: 32rpx;
}
.my-avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  background: #eee;
  margin-right: 32rpx;
}
.my-profile-info {
  flex: 1;
}
.my-profile-name {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 8rpx;
}
.my-profile-desc {
  color: #888;
  font-size: 26rpx;
}
.my-menu {
  background: #fff;
  border-radius: 20rpx;
  margin: 0 24rpx;
  box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.03);
}
.my-menu-item {
  display: flex;
  align-items: center;
  padding: 32rpx 0 32rpx 24rpx;
  border-bottom: 1px solid #f0f0f0;
}
.my-menu-item:last-child {
  border-bottom: none;
}
.my-menu-icon-img {
  width: 40rpx;
  height: 40rpx;
  margin-right: 24rpx;
  display: block;
}
.my-menu-title {
  flex: 1;
  font-size: 32rpx;
}
.my-menu-arrow {
  color: #ccc;
  font-size: 32rpx;
  margin-right: 24rpx;
}
</style>
